﻿using System;
using System.IO;
using System.Security.Cryptography;

public class Util
{
    /// <summary>
    /// 获取md5
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string GetStringHash(string str)
    {
        byte[] data = System.Text.Encoding.Default.GetBytes(str);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] result = md5.ComputeHash(data);
        string fileMD5 = "";
        foreach (byte b in result)
        {
            fileMD5 += Convert.ToString(b, 16);
        }
        return fileMD5;
    }

    /// <summary>
    /// 获取文件的MD5
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static string GetFileMD5(string filePath)
    {
        try
        {
            FileStream fs = new FileStream(filePath, FileMode.Open);
            int len = (int)fs.Length;
            byte[] data = new byte[len];
            fs.Read(data, 0, len);
            fs.Close();
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(data);
            string fileMD5 = "";
            foreach (byte b in result)
            {
                fileMD5 += Convert.ToString(b, 16);
            }
            return fileMD5;
        }
        catch (FileNotFoundException e)
        {
            UnityEngine.Debug.LogError(e.Message);
            return "";
        }
    }

    /// <summary>
    /// 获取文件名（不包含后缀）
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static string GetFileRealName(string filePath)
    {
        //去除空格
        filePath = filePath.Trim();
        //Debug.Log(filePath); 
        //string[] temp0 = filePath.Split('/');
        //string temp1 = temp0[temp0.Length - 1];
        //string[] temp2 = temp1.Split('.');
        ////Debug.Log(temp2[0]);
        //return temp2[0];

        return Path.GetFileNameWithoutExtension(filePath);
    }

    /// <summary>
    /// 获取文件长度（字节数）
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static int GetFileLength(string filePath)
    {
        FileStream fs = new FileStream(filePath, FileMode.Open);
        int len = (int)fs.Length;
        fs.Close();
        return len;
    }
     
}
